<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/27
 * Time: 9:32
 */

namespace App\Http\Controllers\admin_system;

use App\Common\ApiData;
use App\Models\V1\CompanyModel;
use App\Models\V1\MemberModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Module\EntManageuser;
use App\Module\EntReadingParty;
use Cookie;
use DB;
use Maatwebsite\Excel\Facades\Excel;
use Validator;
use Redirect;
use Session;
use App\Models\V1\ReadPartyModel;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;


class ReadingPartyController extends Controller
{
    protected $arrayreaParType = ['', '企业', '爱好', '官方'];
    protected $arrayStates = ['审核中', '审核成功', '审核失败'];

    /**
     * 读书会首页
     * */
    public function index(Request $request)
    {
        $keyword        = $request->input('KeyWords');
        $readPartyModel = new ReadPartyModel();
        $readPartys     = $readPartyModel->get_read_party_list($keyword);
        foreach ($readPartys as $party) {
            $party->countMember = $readPartyModel->count_read_party_number($party->ReaParID);
        }

        return view('admin_system.readingparty.index', [
            'readingparty' => $readPartys,
            'arrayType'    => $this->arrayreaParType,
            'keyword'      => $keyword
        ]);
    }


    /**
     * 编辑读书会
     * */
    public function indexedit(Request $request,$id)
    {

        if($id > 0)
        {
            $readPartyModel = new ReadPartyModel();
            $readPartyInfo  = $readPartyModel->get_read_party_info($id);
            if($readPartyInfo->MemNumber)
            {
                $model      =   new MemberModel();
                $memberInfo = $model->get_member_info_by_member_number($readPartyInfo->MemNumber);
                $readPartyInfo->manager  = $memberInfo->UserName;
            }
            else
            {
                $readPartyInfo->manager = "";
            }
        }
        else
        {
            $readPartyInfo  = new \stdClass();
            $readPartyInfo->ReaParID    = 0;
            $readPartyInfo->States      = 0;
            $readPartyInfo->ReaParType  = 0;
            $readPartyInfo->CompanyName = '';
            $readPartyInfo->ReaParName  = "";
            $readPartyInfo->Regulation  = "";
            $readPartyInfo->manager     = "";
            $readPartyInfo->FilePath1   = "";
            if($request->input('companyId',0) > 0)
            {
                $companyModel   = new CompanyModel();
                $companyInfo    = $companyModel->get_company_info($request->input('companyId'));
                $readPartyInfo->CompanyName = $companyInfo->company_name;
            }
        }


        $arrayReaParType = $this->arrayreaParType;
        $arrayStates     = $this->arrayStates;
        $data = [
            'entReadingParty' => $readPartyInfo,
            'arrayReaParType' => $arrayReaParType,
            'arrayStates'     => $arrayStates
        ];
        return view('admin_system.readingparty.indexEdit', $data);
    }



    /**
     * 修改或添加读书会
     * */
    public function readparty_edit(Request $request)
    {

        $id                 = $request->input('readpartyId');
        $readpartyModel     = $id > 0 ? EntReadingParty::findOrFail($id) : new EntReadingParty;
        $readpartyModel->States      = $request->get('states');
        $readpartyModel->ReaParType  = $request->get('readpartyType');
        $readpartyModel->ReaParName  = trim($request->get('ReaParName'));
        $readpartyModel->Regulation  = trim($request->get('regulation'));
        $readpartyModel->AddDate     = $readpartyModel->AddDate ?? date_time();
        $readpartyModel->MasterID    = $request->session()->get('manageUser')->UserID;
        $readpartyModel->ReleaseDate = date_time();
        $mobile                      = $request->input('manager');
        $companyName                 = $request->input('companyName');

        if($request->get('File_1'))
        {
            $readpartyModel->FilePath1   = $request->get('File_1');
        }

        //1.有管理员 检查管理员是否存在
        if($mobile)
        {
            $memberModel    = new MemberModel();
            $memberInfo     = $memberModel->get_member_info_by_mobile($mobile);
            if(!$memberInfo)
            {
                return apiData()->notice("管理员".$mobile."不存在系统中");
            }
            $readpartyModel->MemNumber  = $memberInfo->MemNumber;
        }




        DB::beginTransaction();
        try {
            $readpartyModel->save();
            DB::commit();
            return apiData()->notice('操作成功');
        } catch (Exception $e) {
            DB::rollBack();
            return apiData()->notice('操作失败');
        }
    }


    public function indexaudit(Request $request)
    {
        $result = '';
        try {
            if ($request->ajax()) {
                $IDList = $request->json('IDList');
                if (is_numeric($IDList)) {
                    EntReadingParty::where('ReaParID', $IDList)->update([
                        'States' => '1'
                    ]);
                    $result = 'ok';
                } else {
                    EntReadingParty::whereIn('ReaParID', explode(',', $IDList))->update([
                        'States' => '1'
                    ]);
                    $result = 'ok';
                }
            }
        } catch (Exception $e) {
            $result = 'no';
        }
        return $result;
    }

    public function indexdelete(Request $request)
    {
        $result = '';
        try {
            if ($request->ajax()) {
                $IDList = $request->json('IDList');
                if (is_numeric($IDList)) {
                    EntReadingParty::where('ReaParID', $IDList)->update([
                        'DeleteMark' => '0'
                    ]);
                    $result = 'ok';
                } else {
                    EntReadingParty::whereIn('ReaParID', explode(',', $IDList))->update([
                        'DeleteMark' => '0'
                    ]);
                    $result = 'ok';
                }
            }
        } catch (Exception $e) {
            $result = 'no';
        }
        return $result;
    }

    public function import_member(Request $request)
    {
        $readPartyId   = $request->input('readId');
        $readModel     = new ReadPartyModel();
        $readPartyInfo = $readModel->get_read_party_info($readPartyId);
        return view('admin_system/readingparty/import-member', ['readPartyInfo' => $readPartyInfo]);
    }

    /**
     * 导入会员到读书会
     * */
    public function import_member_action(Request $request)
    {
        $readId         = $request->input('readId');
        $users          = $request->input('users');
        $users          = json_decode($users);
        $memberModel    = new MemberModel();
        $apiDta         = new ApiData();
        $readPartyModel = new ReadPartyModel();
        $readPartyInfo  = $readPartyModel->get_read_party_info($readId);
        $companyId      = $readPartyInfo->company_id;
        $companyModel   = new CompanyModel();


        //获取所有的部门，查看是否有没有创建的部门
        $departments = $companyModel->get_company_department($companyId,$readId);
        $oldDepartments     = [];
        //反转 用部门来作为key
        foreach($departments as $depart)
        {
            $k = md5($depart->department_name);
            $oldDepartments[$k] = $depart->department_id;
        }


        $errorMobiles   = [];   //错误的号码
        $newDepartments = [];   //新的部门
        //统一检测
        foreach($users as $user)
        {
            $mobile         = trim($user->mobile);
            $user->mobile   = $mobile;

            //收集不符合的号码
            if(!($mobile && preg_match('/^\d{5,20}$/',$mobile)))
            {
                array_push($errorMobiles,$mobile);
                continue;
            }
            //收集所有部门
            $newDepartment      = trim($user->department);
            $user->department   = $newDepartment;

            if( in_array($newDepartment,$newDepartments) == false && isset($oldDepartments[md5($newDepartment)]) == false)
            {
                array_push($newDepartments,$newDepartment);
            }
        }

        if(count($errorMobiles) > 0)
        {
            $apiDta->send(4002,"号码异常:".implode(',',$errorMobiles));
        }


        //创建新的部门
        foreach($newDepartments as $part)
        {
            $partInfo   = [
                'company_id'        => $readPartyInfo->company_id,
                'read_party_id'     => $readId,
                'department_name'   => $part
            ];
            $partId = $companyModel->update_department($partInfo);
            $oldDepartments[md5($part)] = $partId;
        }

        //对全部用户进行判断，检查是否已存在该用户，没有存在则先添加

        $addNumber    = 0;
        $companyModel = new CompanyModel();
        $companyId    = $readPartyInfo->company_id;
        foreach ($users as $user)
        {
            $user->department   = $oldDepartments[md5($user->department)];
            $memberInfo         = $memberModel->get_member_info_by_mobile($user->mobile);
            if($memberInfo == false) //新用户，需要加入系统
            {
                $userName = $user->username;
                $newUserInfo = [
                    "States"        => 1,
                    "UserName"      => $user->mobile,
                    "NickName"      => $userName,
                    "YourName"      => $userName,
                    "RegisterType"  => '内部后台导入',
                    "sex"           => "N",
                ];
                $userId   = $memberModel->register($newUserInfo);
                $user->userId = $userId;
                $addNumber++;
            }else {
                $user->userId   = $memberInfo->UserID;
            }
        }

        foreach($users as $user)
        {
            $userId     = $user->userId;
            $department = $user->department;

            //1.加入公司
            $userCompanyInfo    = $companyModel->get_company_member_info($companyId,$department,$userId);
            $job    = trim($user->job) ? trim($user->job) : "未填写";

            if($userCompanyInfo)
            {
                $companyModel->update_company_member_by_id($userCompanyInfo->company_user_id,['job'=>$job]);
            }else
            {
                $companyModel->add_company_member($companyId,$department,$userId,$job);
            }

            //检查读书会是否存在某用户
            $userReadPartyInfo  = $readPartyModel->get_read_party_member_detail($userId,$readId,$department);
            $readUser           = ['reward_right'=>$user->reward,'look_gift_right'=>$user->giftright];
            if($userReadPartyInfo)
            {
                $readPartyModel->update_read_party_member($userReadPartyInfo->read_user_id,$readUser);
            }
            else
            {
                $readPartyModel->add_read_party_member($readId,$userId,$department,$readUser);
            }

            //重新计算时间
            $memberModel->change_member_endtime($userId);
            $memberModel->update_member_info(['UserID'=>$userId,'States'=>1]);
        }

        return $apiDta->send(200,"导入成功");
    }


    public function add_member(Request $request)
    {
        $readId    = $request->input('readId');
        $readModel = new ReadPartyModel();
        $readInfo  = $readModel->get_read_party_info($readId);
        return view('admin_system/readingparty/add-member', ['readInfo' => $readInfo]);
    }

    public function add_single_member_action(Request $request)
    {
        $readModel        = new ReadPartyModel();
        $readId           = $request->input('readId');
        $userId           = $request->input('userId');
        $rewardRight      = $request->input('right');
        $result           = $readModel->add_read_party_member($readId, $userId, $rewardRight);
        $apiData          = new ApiData();
        $apiData->message = "已加入";
        $apiData->code    = 200;
        return $apiData->send();
    }

    /**
     * 读书会会员
     * */
    public function members(Request $request)
    {
        $readPartyId    = $request->input('readId');
        $page           = $request->input('page', 1);
        $keywords       = trim($request->input('keywords'));
        $readPartyModel = new ReadPartyModel();



        $members        = $readPartyModel->get_read_party_member($readPartyId, $keywords, 0, $page);
        $total          = $readPartyModel->count_read_party_number($readPartyId, $keywords);
        $perPage        = 10; //每页的记录数 ( 常量 )
        $current_page   = $request->input('page', 1);
        $readPartyInfo  = $readPartyModel->get_read_party_info($readPartyId);
        if($readPartyInfo->MemNumber)
        {




        }




        $path      = Paginator::resolveCurrentPath(); // 获取当前的链接"http://localhost/admin/account"
        $paginator = new LengthAwarePaginator($members, $total, $perPage, $current_page, [
            'path'     => $path,  //设定个要分页的url地址。也可以手动通过 $paginator ->setPath(‘路径’) 设置
            'pageName' => 'page', //链接的参数名 http://localhost/admin/manage?page=2
        ]);

        $data = [
            'members'   => $members,
            'paginator' => $paginator,
            'readId'    => $readPartyId,
            'keywords'  => $keywords
        ];
        return view('admin_system/readingparty/members', $data);
    }

    /**
     * 删除读书会会员
     * */
    public function delete_read_party_member(Request $request)
    {
        $readId    = $request->input('readId');
        $userId    = $request->input('userId');
        $apiData   = new ApiData();
        $readModel = new ReadPartyModel();
        $readModel->remove_party_member($readId, $userId);
        $apiData->message = "已将会员移除读书会！";
        $apiData->code    = 200;
        return $apiData->send();
    }

    public function upload(ReadPartyModel $readPartyModel, Request $request)
    {
        $id       = $request->Input('id');
        $cellData = [
            ['用户名字', '手机号', '加入时间', '部门&职位', '打赏权限'],
        ];
        $data     = $readPartyModel->getdown($id);

        $data = array_merge($cellData, $data);

        $readPartyName = DB::table('read_party')->where('ReaParID', $id)->select('ReaParName')->first();
        $readPartyName = $readPartyName->ReaParName ? $readPartyName->ReaParName : '名字缺失了';

        Excel::create('读书会成员信息--' . $readPartyName, function ($excel) use ($data) {
            $excel->sheet('MemberInfo', function ($sheet) use ($data) {
                $sheet->rows($data);
            });
        })->export('xls');

    }
}